package com.xjscrm.console.chat.core.impl;

import cn.hutool.core.util.IdUtil;
import com.uzai.mobile.collect.api.MicaTopics;
import com.uzai.mobile.collect.api.dto.MicaTriggerDto;
import com.uzai.mobile.collect.api.dto.trigger.MicaTriggerForwardMultiRecordMsg;
import com.uzai.mobile.collect.api.enums.MicaTriggerType;
import com.xjscrm.common.entity.WwDevice;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.console.chat.core.ChatBaseMsgHandler;
import com.xjscrm.console.chat.enums.ChatMsgType;
import com.xjscrm.console.chat.frame.recv.RForwardMultiRecordMsg;
import com.xjscrm.console.chat.frame.send.SResultMsg;
import com.xjscrm.console.entity.ChatTalkRecord;
import com.xjscrm.console.entity.ChatTalkSession;
import com.xjscrm.console.mq.producer.SendMsgProducer;
import com.xjscrm.console.service.customer.chat.ChatTalkRecordService;
import com.xjscrm.console.service.customer.chat.ChatTalkSessionService;
import com.xjscrm.console.service.customer.wwDevice.WwDeviceService;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author mingyang.chen create in 2024/3/12 09:41
 */
@Component
@Slf4j
public class ChatForwardMultiRecordMsgHandler extends ChatBaseMsgHandler<RForwardMultiRecordMsg> {

    @Autowired
    private WwDeviceService deviceService;

    @Autowired
    private SendMsgProducer sendMsgProducer;

    @Autowired
    private ChatTalkRecordService chatTalkRecordService;

    @Autowired
    private ChatTalkSessionService chatTalkSessionService;

    @Override
    public SResultMsg doHandle(RForwardMultiRecordMsg content, ChannelHandlerContext ctx) {


        Long merId = content.getMerId();
        List<Long> recordIds = content.getRecordIds();
        Long talkSessionId = content.getTalkSessionId();
        Long deviceUniqueId = content.getDeviceUniqueId();
        List<String> recvWxIds = content.getRecvWxIds();

        try {
            WwDevice byId = deviceService.getById(merId, deviceUniqueId);
            if (Objects.isNull(byId)) {
                throw new BusinessException("机器人设备未找到");
            }
            //
            List<ChatTalkRecord> chatTalkRecords = chatTalkRecordService.listByIds(merId, recordIds, talkSessionId);
            if (ObjectUtils.isEmpty(chatTalkRecords)) {
                return SResultMsg.fail(content, "批量转发失败: 聊天记录不存在");
            }
            ChatTalkSession talkSession = chatTalkSessionService.getById(merId, talkSessionId);
            if (Objects.isNull(talkSession)) {
                return SResultMsg.fail(content, "批量转发失败: 会话不存在");
            }

            List<Long> msgIds = chatTalkRecords.stream().map(ChatTalkRecord::getRemoteMsgId).collect(Collectors.toList());

            MicaTriggerForwardMultiRecordMsg micaTriggerForwardMultiRecordMsg = new MicaTriggerForwardMultiRecordMsg();

            micaTriggerForwardMultiRecordMsg.setMsgId(msgIds);
            micaTriggerForwardMultiRecordMsg.setConversationId(talkSession.getConversationId());
            micaTriggerForwardMultiRecordMsg.setWxIds(recvWxIds);

            MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerForwardMultiRecordMsg, MicaTriggerType.TRIGGER_FORWARD_MULTI_RECORD, item -> {
                item.setReqId(IdUtil.getSnowflakeNextId());
                item.setDeviceId(byId.getDeviceId());
                item.setDeviceType(byId.getDeviceType());
            });
            sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);

            return SResultMsg.success(content, "批量转发消息中");
        } catch (Exception e) {
            log.error("批量转发消息失败", e);
            throw new BusinessException("批量转发消息失败");
        }
    }

    @Override
    public boolean checkMsg(RForwardMultiRecordMsg baseMsg) {
        return super.checkMsg(baseMsg) || !ObjectUtils.allNotNull(baseMsg.getDeviceUniqueId(), baseMsg.getTalkSessionId()) || ObjectUtils.isEmpty(baseMsg.getRecordIds());
    }

    @Override
    public Class<RForwardMultiRecordMsg> msgClass() {
        return RForwardMultiRecordMsg.class;
    }

    @Override
    public ChatMsgType msgType() {
        return ChatMsgType.r_forward_multi_record;
    }
}
